🎨 Advanced ggplot2 - Part 2

Themes və Publication-Ready Graphics

# Recreate dataset from Part 1
set.seed(2024)
n <- 200

academic_data <- data.frame(
  student_id = 1:n,
  age = sample(18:25, n, replace = TRUE),
  gender = sample(c("Male", "Female"), n, replace = TRUE),
  faculty = sample(c("Engineering", "Medicine", "Economics", "IT"), n, replace = TRUE),
  math_score = round(rnorm(n, 75, 15), 1),
  physics_score = round(rnorm(n, 72, 16), 1),
  gpa = round(runif(n, 2.0, 4.0), 2),
  study_hours_week = round(pmax(5, rnorm(n, 30, 10)), 1),
  life_satisfaction = round(runif(n, 1, 10), 1),
  stress_level = round(runif(n, 1, 10), 1),
  family_income = round(pmax(1000, rnorm(n, 3000, 1000))),
  stringsAsFactors = FALSE
)

academic_data$total_score <- academic_data$math_score + academic_data$physics_score
academic_data$performance_level <- cut(academic_data$gpa, 
                                      breaks = c(0, 2.5, 3.0, 3.5, 4.0),
                                      labels = c("Below Average", "Average", "Good", "Excellent"))

cat("Dataset Part 2 üçün hazır:", nrow(academic_data), "tələbə\n")
#> Dataset Part 2 üçün hazır: 200 tələbə

1 Themes və Customization

1.1 Built-in Themes

# Create sample data for theme demonstration
sample_data <- academic_data[sample(nrow(academic_data), 40), ]

par(mfrow = c(2, 2))

# 1. Minimal style
plot(sample_data$math_score, sample_data$gpa,
     main = "theme_minimal() Style",
     xlab = "Math Score", ylab = "GPA",
     pch = 16, col = "steelblue",
     panel.first = grid(col = "lightgray", lty = "dotted"))
box(col = "gray50")

# 2. Classic style  
plot(sample_data$math_score, sample_data$gpa,
     main = "theme_classic() Style",
     xlab = "Math Score", ylab = "GPA",
     pch = 16, col = "steelblue")

# 3. Dark theme
plot(sample_data$math_score, sample_data$gpa,
     main = "theme_dark() Style",
     xlab = "Math Score", ylab = "GPA",
     pch = 16, col = "lightblue",
     bg = "gray20", fg = "white", col.main = "white",
     col.lab = "white", col.axis = "white")

# 4. Publication ready
plot(sample_data$math_score, sample_data$gpa,
     main = "Publication Style",
     xlab = "Math Score", ylab = "GPA",
     pch = 16, col = "black", cex = 0.8,
     panel.first = {
       grid(col = "gray90")
       rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
            col = "gray98", border = "black")
     })

par(mfrow = c(1, 1))

cat("ggplot2 themes:\n")
#> ggplot2 themes:
cat("p <- ggplot(data, aes(x = math_score, y = gpa)) + geom_point()\n")
#> p <- ggplot(data, aes(x = math_score, y = gpa)) + geom_point()
cat("p + theme_minimal()  # Clean design\n")
#> p + theme_minimal()  # Clean design
cat("p + theme_classic()  # Classic look\n")
#> p + theme_classic()  # Classic look
cat("p + theme_dark()     # Dark background\n")
#> p + theme_dark()     # Dark background
cat("p + theme_bw()       # Black and white\n")
#> p + theme_bw()       # Black and white

1.2 Custom Theme Creation

# Academic theme
create_academic_plot <- function(x, y, title, xlab, ylab) {
  plot(x, y, main = title, xlab = xlab, ylab = ylab,
       pch = 16, col = rgb(0.2, 0.4, 0.6, 0.7), cex = 1.1,
       panel.first = {
         rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
              col = rgb(0.95, 0.97, 1.0), border = NA)
         grid(col = rgb(1, 1, 1, 0.8), lwd = 1)
       },
       col.main = "navy", font.main = 2, cex.main = 1.3,
       col.lab = "darkblue", font.lab = 2)
  box(col = "navy", lwd = 2)
}

create_academic_plot(academic_data$math_score, academic_data$gpa,
                    "Academic Performance Analysis",
                    "Mathematics Score", "GPA")

cat("ggplot2 academic theme:\n")
#> ggplot2 academic theme:
cat("theme_academic <- function() {\n")
#> theme_academic <- function() {
cat("  theme_minimal() +\n")
#>   theme_minimal() +
cat("  theme(\n")
#>   theme(
cat("    panel.background = element_rect(fill = '#F5F7FF'),\n")
#>     panel.background = element_rect(fill = '#F5F7FF'),
cat("    plot.background = element_rect(color = 'navy', size = 2),\n")
#>     plot.background = element_rect(color = 'navy', size = 2),
cat("    panel.grid = element_line(color = 'white'),\n")
#>     panel.grid = element_line(color = 'white'),
cat("    plot.title = element_text(color = 'navy', face = 'bold'),\n")
#>     plot.title = element_text(color = 'navy', face = 'bold'),
cat("    axis.title = element_text(color = 'darkblue', face = 'bold')\n")
#>     axis.title = element_text(color = 'darkblue', face = 'bold')
cat("  )\n")
#>   )
cat("}\n")
#> }
# Corporate theme
create_corporate_plot <- function(x, y, title, xlab, ylab) {
  plot(x, y, main = title, xlab = xlab, ylab = ylab,
       pch = 15, col = rgb(0.1, 0.1, 0.1, 0.8), cex = 1.0,
       panel.first = {
         rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
              col = "white", border = NA)
         grid(col = "gray95", lwd = 0.5)
       },
       col.main = "#2C3E50", cex.main = 1.2,
       col.lab = "#34495E", col.axis = "#7F8C8D")
  box(col = "#BDC3C7")
}

create_corporate_plot(academic_data$family_income, academic_data$gpa,
                     "Income Impact on Performance",
                     "Family Income", "GPA")

cat("\nCorporate theme:\n")
#> 
#> Corporate theme:
cat("theme_corporate <- function() {\n")
#> theme_corporate <- function() {
cat("  theme_minimal() +\n")
#>   theme_minimal() +
cat("  theme(\n")
#>   theme(
cat("    panel.background = element_rect(fill = 'white'),\n")
#>     panel.background = element_rect(fill = 'white'),
cat("    panel.grid = element_line(color = 'gray95'),\n")
#>     panel.grid = element_line(color = 'gray95'),
cat("    plot.title = element_text(color = '#2C3E50'),\n")
#>     plot.title = element_text(color = '#2C3E50'),
cat("    axis.title = element_text(color = '#34495E'),\n")
#>     axis.title = element_text(color = '#34495E'),
cat("    legend.position = 'bottom'\n")
#>     legend.position = 'bottom'
cat("  )\n")
#>   )
cat("}\n")
#> }

1.3 Element Modifications

# Text elements
plot(academic_data$age, academic_data$life_satisfaction,
     main = "", xlab = "", ylab = "",
     pch = 16, col = rgb(0.3, 0.7, 0.9, 0.7), cex = 1.2)

title(main = "Student Wellbeing Analysis", 
      col.main = "#2C3E50", cex.main = 1.4, font.main = 2)
title(sub = "Age vs Life Satisfaction", 
      col.sub = "gray50", cex.sub = 1.0, font.sub = 3)
title(xlab = "Student Age", col.lab = "#34495E", cex.lab = 1.1, font.lab = 2)
title(ylab = "Life Satisfaction Score", col.lab = "#34495E", cex.lab = 1.1, font.lab = 2)

cat("ggplot2 text elements:\n")
#> ggplot2 text elements:
cat("ggplot(data, aes(x = age, y = life_satisfaction)) +\n")
#> ggplot(data, aes(x = age, y = life_satisfaction)) +
cat("  geom_point() +\n")
#>   geom_point() +
cat("  labs(\n")
#>   labs(
cat("    title = 'Student Wellbeing Analysis',\n")
#>     title = 'Student Wellbeing Analysis',
cat("    subtitle = 'Age vs Life Satisfaction',\n")
#>     subtitle = 'Age vs Life Satisfaction',
cat("    x = 'Student Age',\n")
#>     x = 'Student Age',
cat("    y = 'Life Satisfaction Score'\n")
#>     y = 'Life Satisfaction Score'
cat("  ) +\n")
#>   ) +
cat("  theme(\n")
#>   theme(
cat("    plot.title = element_text(size = 16, face = 'bold'),\n")
#>     plot.title = element_text(size = 16, face = 'bold'),
cat("    plot.subtitle = element_text(color = 'gray50')\n")
#>     plot.subtitle = element_text(color = 'gray50')
cat("  )\n")
#>   )
# Axis customization
plot(academic_data$total_score, academic_data$gpa,
     main = "Customized Axes",
     xlab = "Total Score", ylab = "GPA",
     pch = 21, bg = "lightcoral", col = "darkred",
     axes = FALSE)

axis(1, col = "darkred", col.axis = "darkred", cex.axis = 0.9)
axis(2, col = "darkred", col.axis = "darkred", cex.axis = 0.9)
box(col = "darkred")

cat("\nAxis customization:\n")
#> 
#> Axis customization:
cat("theme(\n")
#> theme(
cat("  axis.text = element_text(color = 'darkred', face = 'bold'),\n")
#>   axis.text = element_text(color = 'darkred', face = 'bold'),
cat("  axis.line = element_line(color = 'darkred'),\n")
#>   axis.line = element_line(color = 'darkred'),
cat("  panel.grid = element_line(color = 'gray90', linetype = 'dotted')\n")
#>   panel.grid = element_line(color = 'gray90', linetype = 'dotted')
cat(")\n")
#> )

2 Publication-Ready Graphics

2.1 Academic Journal Style

# High-quality academic figure
par(mar = c(5, 5, 4, 2))

plot(academic_data$study_hours_week, academic_data$gpa,
     main = "",
     xlab = "", ylab = "",
     pch = 21, bg = "gray70", col = "black", cex = 0.8,
     panel.first = {
       rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
            col = "white", border = "black")
       grid(col = "gray90", lty = 1, lwd = 0.5)
     })

# Add regression line
lm_pub <- lm(gpa ~ study_hours_week, data = academic_data)
abline(lm_pub, col = "black", lwd = 2)

# Professional labels
title(main = "Study Hours and Academic Performance", 
      cex.main = 1.1, font.main = 1)
title(xlab = "Study Hours per Week", cex.lab = 1.0)
title(ylab = "Grade Point Average", cex.lab = 1.0)

# Statistics
r_squared <- summary(lm_pub)$r.squared
correlation <- cor(academic_data$study_hours_week, academic_data$gpa)
n_obs <- nrow(academic_data)

text(45, 3.8, sprintf("R² = %.3f", r_squared), cex = 0.9)
text(45, 3.7, sprintf("r = %.3f", correlation), cex = 0.9)
text(45, 3.6, sprintf("n = %d", n_obs), cex = 0.9)

cat("Publication style:\n")
#> Publication style:
cat("ggplot(data, aes(x = study_hours_week, y = gpa)) +\n")
#> ggplot(data, aes(x = study_hours_week, y = gpa)) +
cat("  geom_point(shape = 21, fill = 'gray70', color = 'black') +\n")
#>   geom_point(shape = 21, fill = 'gray70', color = 'black') +
cat("  geom_smooth(method = 'lm', color = 'black', se = FALSE) +\n")
#>   geom_smooth(method = 'lm', color = 'black', se = FALSE) +
cat("  theme_classic() +\n")
#>   theme_classic() +
cat("  theme(\n")
#>   theme(
cat("    plot.title = element_text(size = 11, hjust = 0.5),\n")
#>     plot.title = element_text(size = 11, hjust = 0.5),
cat("    axis.title = element_text(size = 10),\n")
#>     axis.title = element_text(size = 10),
cat("    panel.background = element_rect(fill = 'white', color = 'black')\n")
#>     panel.background = element_rect(fill = 'white', color = 'black')
cat("  )\n")
#>   )
# Multi-panel figure
par(mfrow = c(2, 2), mar = c(4, 4, 3, 2))

# Panel A: Distribution
hist(academic_data$gpa, breaks = 15, 
     main = "A) GPA Distribution", 
     xlab = "GPA", ylab = "Frequency",
     col = "gray80", border = "black")

# Panel B: Scatter
plot(academic_data$math_score, academic_data$physics_score,
     main = "B) Math vs Physics",
     xlab = "Math Score", ylab = "Physics Score",
     pch = 16, col = "gray50")
abline(lm(physics_score ~ math_score, data = academic_data), col = "black", lwd = 2)

# Panel C: Box plot
boxplot(gpa ~ performance_level, data = academic_data,
        main = "C) GPA by Performance",
        xlab = "Performance Level", ylab = "GPA",
        col = "gray80")

# Panel D: Bar plot
performance_counts <- table(academic_data$performance_level)
barplot(performance_counts,
        main = "D) Performance Distribution",
        xlab = "Performance Level", ylab = "Count",
        col = "gray80")

par(mfrow = c(1, 1))

cat("\nMulti-panel figure:\n")
#> 
#> Multi-panel figure:
cat("library(gridExtra)\n")
#> library(gridExtra)
cat("p1 <- ggplot() + geom_histogram()\n")
#> p1 <- ggplot() + geom_histogram()
cat("p2 <- ggplot() + geom_point()\n")
#> p2 <- ggplot() + geom_point()
cat("p3 <- ggplot() + geom_boxplot()\n")
#> p3 <- ggplot() + geom_boxplot()
cat("p4 <- ggplot() + geom_bar()\n")
#> p4 <- ggplot() + geom_bar()
cat("grid.arrange(p1, p2, p3, p4, ncol = 2)\n")
#> grid.arrange(p1, p2, p3, p4, ncol = 2)

2.2 Interactive Elements və Export

# Interactive simulation
plot(academic_data$total_score, academic_data$life_satisfaction,
     main = "Interactive Analysis Simulation",
     xlab = "Total Score", ylab = "Life Satisfaction",
     pch = 21, bg = rgb(0.3, 0.6, 0.9, 0.7), col = "darkblue", cex = 1.2)

# Simulate tooltip
highlight_student <- academic_data[50, ]
points(highlight_student$total_score, highlight_student$life_satisfaction,
       pch = 21, bg = "yellow", col = "red", cex = 2)

tooltip_text <- paste(
  "ID:", highlight_student$student_id,
  "\nFaculty:", highlight_student$faculty,
  "\nGPA:", highlight_student$gpa
)

text(highlight_student$total_score + 15, highlight_student$life_satisfaction,
     tooltip_text, pos = 4, cex = 0.8,
     bg = "lightyellow", box.col = "orange")

cat("Interactive plots:\n")
#> Interactive plots:
cat("library(plotly)\n")
#> library(plotly)
cat("p <- ggplot(data, aes(x = total_score, y = life_satisfaction,\n")
#> p <- ggplot(data, aes(x = total_score, y = life_satisfaction,
cat("                     text = paste('Student:', student_id))) +\n")
#>                      text = paste('Student:', student_id))) +
cat("  geom_point() +\n")
#>   geom_point() +
cat("  labs(title = 'Interactive Analysis')\n")
#>   labs(title = 'Interactive Analysis')
cat("ggplotly(p, tooltip = 'text')\n")
#> ggplotly(p, tooltip = 'text')
# Dashboard simulation
par(mfrow = c(2, 3), mar = c(4, 4, 3, 2))

# 1. GPA distribution
hist(academic_data$gpa, breaks = 10, main = "GPA Distribution",
     col = rgb(0.3, 0.7, 0.9, 0.7), border = "darkblue")

# 2. Faculty performance
faculty_means <- aggregate(gpa ~ faculty, data = academic_data, mean)
barplot(faculty_means$gpa, names.arg = faculty_means$faculty,
        main = "Average GPA by Faculty", las = 2,
        col = rainbow(nrow(faculty_means), alpha = 0.7))

# 3. Study hours vs GPA
plot(academic_data$study_hours_week, academic_data$gpa,
     main = "Study vs Performance", pch = 16,
     col = rgb(0.6, 0.4, 0.8, 0.6))

# 4. Stress vs satisfaction
plot(academic_data$stress_level, academic_data$life_satisfaction,
     main = "Stress vs Satisfaction", pch = 16,
     col = rgb(0.8, 0.4, 0.4, 0.6))

# 5. Performance pie
pie(table(academic_data$performance_level), 
    main = "Performance Distribution",
    col = c("red", "orange", "lightgreen", "darkgreen"))

# 6. Subject scores
subjects <- c("Math" = mean(academic_data$math_score),
              "Physics" = mean(academic_data$physics_score))
barplot(subjects, main = "Average Scores", 
        col = c("#E74C3C", "#3498DB"))

par(mfrow = c(1, 1))

cat("\nDashboard creation:\n")
#> 
#> Dashboard creation:
cat("library(shiny)\n")
#> library(shiny)
cat("ui <- fluidPage(\n")
#> ui <- fluidPage(
cat("  selectInput('faculty', 'Faculty:', choices = unique(data$faculty)),\n")
#>   selectInput('faculty', 'Faculty:', choices = unique(data$faculty)),
cat("  plotOutput('plot')\n")
#>   plotOutput('plot')
cat(")\n")
#> )
cat("server <- function(input, output) {\n")
#> server <- function(input, output) {
cat("  output$plot <- renderPlot({\n")
#>   output$plot <- renderPlot({
cat("    filtered <- data[data$faculty == input$faculty, ]\n")
#>     filtered <- data[data$faculty == input$faculty, ]
cat("    ggplot(filtered, aes(x = math_score, y = gpa)) + geom_point()\n")
#>     ggplot(filtered, aes(x = math_score, y = gpa)) + geom_point()
cat("  })\n")
#>   })
cat("}\n")
#> }
# Export options
cat("\nExport formats:\n")
#> 
#> Export formats:
cat("# High-quality PNG\n")
#> # High-quality PNG
cat("png('figure.png', width = 8, height = 6, units = 'in', res = 300)\n")
#> png('figure.png', width = 8, height = 6, units = 'in', res = 300)
cat("your_plot_code()\n")
#> your_plot_code()
cat("dev.off()\n\n")
#> dev.off()
cat("# PDF for publications\n")
#> # PDF for publications
cat("pdf('figure.pdf', width = 8, height = 6)\n")
#> pdf('figure.pdf', width = 8, height = 6)
cat("your_plot_code()\n")
#> your_plot_code()
cat("dev.off()\n\n")
#> dev.off()
cat("# ggplot2 exports\n")
#> # ggplot2 exports
cat("ggsave('plot.png', plot = p, width = 8, height = 6, dpi = 300)\n")
#> ggsave('plot.png', plot = p, width = 8, height = 6, dpi = 300)
cat("ggsave('plot.pdf', plot = p, width = 8, height = 6)\n")
#> ggsave('plot.pdf', plot = p, width = 8, height = 6)

2.3 Praktik Tapşırıqlar

# Create a comprehensive example
cat("=== PRATİK TAPŞırıq ÖRNƏYİ ===\n")
#> === PRATİK TAPŞırıq ÖRNƏYİ ===
# Final comprehensive plot
plot(academic_data$study_hours_week, academic_data$gpa,
     main = "Final Analysis: Study Habits and Academic Success",
     xlab = "Weekly Study Hours", ylab = "Grade Point Average",
     pch = 21, 
     bg = ifelse(academic_data$performance_level == "Excellent", "darkgreen",
                ifelse(academic_data$performance_level == "Good", "lightgreen",
                      ifelse(academic_data$performance_level == "Average", "orange", "red"))),
     col = "black", cex = 1.2,
     panel.first = {
       rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
            col = "gray98", border = "gray80")
       grid(col = "white", lwd = 1)
     })

# Add trend line
abline(lm(gpa ~ study_hours_week, data = academic_data), 
       col = "blue", lwd = 3, lty = 2)

# Legend
legend("bottomright",
       legend = c("Excellent", "Good", "Average", "Below Average"),
       pch = 21, pt.bg = c("darkgreen", "lightgreen", "orange", "red"),
       pt.cex = 1.2, bg = "white", box.col = "gray")

# Add summary statistics
r_val <- cor(academic_data$study_hours_week, academic_data$gpa, use = "complete.obs")
text(15, 3.8, paste("Correlation: r =", round(r_val, 3)), 
     font = 2, cex = 1.1, col = "blue")

cat("Comprehensive ggplot2 equivalent:\n")
#> Comprehensive ggplot2 equivalent:
cat("ggplot(academic_data, aes(x = study_hours_week, y = gpa)) +\n")
#> ggplot(academic_data, aes(x = study_hours_week, y = gpa)) +
cat("  geom_point(aes(fill = performance_level), shape = 21, size = 3) +\n")
#>   geom_point(aes(fill = performance_level), shape = 21, size = 3) +
cat("  geom_smooth(method = 'lm', color = 'blue', linetype = 'dashed') +\n")
#>   geom_smooth(method = 'lm', color = 'blue', linetype = 'dashed') +
cat("  scale_fill_manual(values = c('red', 'orange', 'lightgreen', 'darkgreen')) +\n")
#>   scale_fill_manual(values = c('red', 'orange', 'lightgreen', 'darkgreen')) +
cat("  labs(\n")
#>   labs(
cat("    title = 'Study Habits and Academic Success',\n")
#>     title = 'Study Habits and Academic Success',
cat("    x = 'Weekly Study Hours',\n")
#>     x = 'Weekly Study Hours',
cat("    y = 'Grade Point Average',\n")
#>     y = 'Grade Point Average',
cat("    fill = 'Performance Level'\n")
#>     fill = 'Performance Level'
cat("  ) +\n")
#>   ) +
cat("  theme_minimal() +\n")
#>   theme_minimal() +
cat("  theme(\n")
#>   theme(
cat("    plot.title = element_text(size = 14, face = 'bold', hjust = 0.5),\n")
#>     plot.title = element_text(size = 14, face = 'bold', hjust = 0.5),
cat("    panel.background = element_rect(fill = 'gray98', color = 'gray80'),\n")
#>     panel.background = element_rect(fill = 'gray98', color = 'gray80'),
cat("    panel.grid = element_line(color = 'white'),\n")
#>     panel.grid = element_line(color = 'white'),
cat("    legend.position = 'bottom'\n")
#>     legend.position = 'bottom'
cat("  )\n")
#>   )

🎯 Modul 10 Tam Xülasəsi

Bu modulda öyrəndiklərimiz:

  • Part 1: Advanced geometries, aesthetics, statistical layers
  • Part 2: Themes, customization, publication graphics
  • Built-in və custom theme yaradılması
  • Professional figure standartları
  • Interactive visualization konseptləri
  • Export və sharing metodları

📚 Praktik Tapşırıqlar

Başlanğıc səviyyə:

  1. Öz dataset-iniz üçün custom theme yaradın
  2. Publication-ready scatter plot düzəldin
  3. Multi-panel figure hazırlayın

Orta səviyyə:

  1. Interactive dashboard prototipi yaradın
  2. Corporate theme sistemi inkişaf etdirin
  3. Automated report template-i

Qabaqcıl səviyyə:

  1. Custom ggplot2 extension function-ları
  2. Professional portfolio graphics
  3. Publication workflow automation

🎉 Advanced ggplot2 Modulunu Tamamladınız!

Professional və publication-ready visualization-lar yaratmağı öyrəndiniz.

Növbəti addım: Real layihələrdə tətbiq və portfolio yaratmaq

Data visualization journey-nizə uğurlar!

3 Legend customization

faculty_colors <- c(“Engineering” = “#E74C3C”, “Medicine” = “#3498DB”, “Economics” = “#2ECC71”, “IT” = “#9B59B6”)

plot(academic_data\(math_score, academic_data\)gpa, main = “Faculty Performance”, xlab = “Math Score”, ylab = “GPA”, pch = 16, col = faculty_colors[academic_data$faculty], cex = 1.1)

legend(“bottomright”, legend = names(faculty_colors), col = faculty_colors, pch = 16, cex = 0.8, bg = “white”, box.col = “gray50”, title = “Faculty”)

cat(“customization:”) cat(“theme(”) cat(” legend.position = ‘bottom’,“) cat(” legend.title = element_text(face = ‘bold’),“) cat(” legend.background = element_rect(fill = ‘white’, color = ‘gray50’)“) cat(”)“)